package com.sunlee.common.core.redis;

import com.sunlee.common.core.redis.serializer.JsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * Redis 配置
 *
 * @author sunlee
 */
@Configuration
public class RedisConfig {

    @Resource
    private RedisConnectionFactory factory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        //配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        JsonRedisSerializer<Object> objectJsonRedisSerializer = new JsonRedisSerializer<>(Object.class);

        //key序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //value序列化
        redisTemplate.setValueSerializer(objectJsonRedisSerializer);
        //Hash key序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //Hash value序列化
        redisTemplate.setHashValueSerializer(objectJsonRedisSerializer);

        redisTemplate.setConnectionFactory(factory);

        return redisTemplate;
    }
}